import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_chat_ui/pages/chat_room_controller.dart';
import 'package:flutter_chat_ui/utils/x_load_svg.dart';
import 'package:flutter_chat_ui/views/chat_bottom_widgets/chat_text_input_view.dart';
import 'package:flutter_chat_ui/views/chat_bottom_widgets/hold_speech_button_view.dart';
import 'package:get/get.dart';

class ChatBottomView extends StatefulWidget {
  /// 键盘出现/消失回调
  final ValueChanged<double>? onKeyboardStateChanged;

  /// 文本输入
  final ValueChanged<String>? onChange;

  /// 发送消息
  final ValueChanged<String>? onSendMessage;

  /// 停止此次响应
  final VoidCallback? onStopResponse;

  const ChatBottomView({
    super.key,
    this.onKeyboardStateChanged,
    this.onChange,
    this.onSendMessage,
    this.onStopResponse,
  });

  @override
  State<ChatBottomView> createState() => _ChatBottomViewState();
}

class _ChatBottomViewState extends State<ChatBottomView>
    with WidgetsBindingObserver, AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  final TextEditingController _textInputController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool _initialized = false;
  double _initialSafeArea = 0;
  double _previousKeyboardHeight = 0;
  Timer? _keyboardDebounceTimer;

  // 是否显示语音按钮
  final ValueNotifier<bool> _showVoiceNotifier = ValueNotifier(false);

  // 预创建的组件实例，避免重复创建
  late final Widget _chatTextInputView;
  late final Widget _holdSpeakView;

  // 缓存按钮实例，避免重复创建
  late final Widget _voiceButton;
  late final Widget _keyboardButton;
  late final Widget _stopButton;

  // 缓存MediaQuery数据，避免重复查询
  late EdgeInsets _cachedPadding;

  // 键盘动画控制器 - 提升键盘弹出流畅度
  late AnimationController _keyboardAnimationController;

  // 键盘状态
  bool _isKeyboardVisible = false;

  // 保持状态活跃
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    // 初始化键盘动画控制器 - 提升键盘弹出流畅度
    _keyboardAnimationController = AnimationController(
      duration: const Duration(milliseconds: 250),
      vsync: this,
    );

    // 预创建组件实例，避免重复创建
    _initializeComponents();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!_initialized) {
      _initialSafeArea = MediaQuery.of(context).padding.bottom;
      // 缓存MediaQuery数据，避免重复查询
      _cachedPadding = MediaQuery.of(context).padding;
      _initialized = true;
    }
  }

  /// 应用尺寸改变时回调，例如旋转 键盘 - 优化键盘动画流畅度
  @override
  void didChangeMetrics() {
    if (!mounted) return;

    final keyboardHeight = View.of(context).viewInsets.bottom;
    final pixelRatio = View.of(context).devicePixelRatio;

    // 减少不必要的计算和回调，提高精度阈值
    if ((keyboardHeight - _previousKeyboardHeight).abs() < 0.5) return;

    final adjustedHeight = max(keyboardHeight / pixelRatio - _initialSafeArea, 0);
    final wasKeyboardVisible = _isKeyboardVisible;
    _isKeyboardVisible = adjustedHeight > 0;
    _previousKeyboardHeight = keyboardHeight;

    // 键盘状态变化时触发动画
    if (wasKeyboardVisible != _isKeyboardVisible) {
      if (_isKeyboardVisible) {
        _keyboardAnimationController.forward();
      } else {
        _keyboardAnimationController.reverse();
      }
    }

    // 取消防抖，使用SchedulerBinding确保在合适的时机执行
    _keyboardDebounceTimer?.cancel();

    // 使用SchedulerBinding.instance.addPostFrameCallback确保在渲染完成后执行
    SchedulerBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        widget.onKeyboardStateChanged?.call(adjustedHeight.toDouble());
      }
    });

    super.didChangeMetrics();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _keyboardDebounceTimer?.cancel();
    _keyboardAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // AutomaticKeepAliveClientMixin 需要调用

    return RepaintBoundary(
      child: Container(
        padding: EdgeInsets.only(
          top: 12,
          bottom: _initialized ? _cachedPadding.bottom + 12 : MediaQuery.of(context).padding.bottom + 12,
        ),
        decoration: const BoxDecoration(
          color: Color(0xffF7F7F7),
          border: Border(
            top: BorderSide(width: 1, color: Color(0xffdddddd)),
          ),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            /// 语音/键盘切换按钮 - 使用预创建的按钮实例
            SizedBox(
              width: 50,
              child: ValueListenableBuilder<bool>(
                valueListenable: _showVoiceNotifier,
                builder: (context, showVoice, child) {
                  return AnimatedSwitcher(
                    duration: const Duration(milliseconds: 200),
                    transitionBuilder: (child, animation) {
                      return ScaleTransition(
                        scale: animation,
                        child: child,
                      );
                    },
                    child: showVoice ? _keyboardButton : _voiceButton,
                  );
                },
              ),
            ),

            /// 输入框 - 使用IndexedStack避免重复创建组件
            Expanded(
              child: ValueListenableBuilder<bool>(
                valueListenable: _showVoiceNotifier,
                builder: (context, showVoice, child) {
                  return IndexedStack(
                    index: showVoice ? 1 : 0,
                    children: [
                      // 0: 文本输入框
                      _chatTextInputView,
                      // 1: 语音输入
                      _holdSpeakView,
                    ],
                  );
                },
              ),
            ),

            /// 发送/暂停按钮 - 优化嵌套的GetX
            _buildActionButton(),
          ],
        ),
      ),
    );
  }

  /// 初始化组件实例。预创建输入组件
  void _initializeComponents() {
    // 输入框
    _chatTextInputView = RepaintBoundary(
      child: ChatTextInputView(
        controller: _textInputController,
        focusNode: _focusNode,
        onChanged: widget.onChange,
        onSubmitted: (value) {
          // 发送消息
          if (value.isNotEmpty) {
            _handlerSendMessage(value);
          }
        },
      ),
    );
    // 按住 说话按钮
    _holdSpeakView = const RepaintBoundary(
      child: HoldSpeechButtonView(),
    );

    /// 预创建按钮实例，添加key避免重复创建
    // 语音按钮
    _voiceButton = RepaintBoundary(
      child: _SvgButtonWidget(
        key: const ValueKey('voice_button'),
        iconName: 'icon_chat_voice',
        onPressed: _handlerToggleInputMode,
      ),
    );
    // 键盘按钮
    _keyboardButton = RepaintBoundary(
      child: _SvgButtonWidget(
        key: const ValueKey('keyboard_button'),
        iconName: 'icon_chat_keyboard',
        onPressed: _handlerToggleInputMode,
      ),
    );
    // 停止按钮
    _stopButton = RepaintBoundary(
      child: _SvgButtonWidget(
        key: const ValueKey('stop_button'),
        iconName: 'icon_stop',
        onPressed: widget.onStopResponse,
      ),
    );
  }

  ///
  /// 构建操作按钮（发送/暂停）- 使用预创建实例优化性能
  ///
  Widget _buildActionButton() {
    return GetX<ChatRoomController>(
      builder: (controller) {
        if (controller.isResponding.value) {
          return _stopButton;
        }

        // 发送按钮根据文本状态动态变化，但使用缓存的颜色值
        return RepaintBoundary(
          child: _SvgButtonWidget(
            iconName: 'icon_send',
            color: controller.isTextEmpty.value ? Colors.grey : Colors.black,
            onPressed: controller.isTextEmpty.value ? null : _handleSendButtonPressed,
          ),
        );
      },
    );
  }

  ///
  /// 切换输入模式 - 优化键盘弹出流畅度
  ///
  void _handlerToggleInputMode() {
    final newValue = !_showVoiceNotifier.value;
    _showVoiceNotifier.value = newValue;

    // 切换到文本输入时，使用优化的聚焦策略
    if (!newValue) {
      // 使用SchedulerBinding确保在合适的时机聚焦，避免卡顿
      SchedulerBinding.instance.addPostFrameCallback((_) {
        if (mounted && !_focusNode.hasFocus) {
          // 延迟聚焦，让UI先完成切换动画
          Future.delayed(const Duration(milliseconds: 100), () {
            if (mounted) {
              _focusNode.requestFocus();
            }
          });
        }
      });
    } else {
      // 切换到语音时，立即取消焦点避免键盘闪烁
      if (_focusNode.hasFocus) {
        _focusNode.unfocus();
      }
    }
  }

  ///
  /// 处理发送按钮点击 - 提取为独立方法避免重复创建闭包
  ///
  void _handleSendButtonPressed() {
    final text = _textInputController.text;
    if (text.isNotEmpty) {
      _handlerSendMessage(text);
      // 收起键盘
      _focusNode.unfocus();
    }
  }

  ///
  /// 发送消息
  ///
  void _handlerSendMessage(String query) {
    widget.onSendMessage?.call(query);
    // 清文本输入框
    _textInputController.clear();
  }
}

///
/// 优化的图片按钮widget - 添加缓存和性能优化
///
class _SvgButtonWidget extends StatelessWidget {
  final String iconName;
  final Color color;
  final VoidCallback? onPressed;

  const _SvgButtonWidget({
    super.key,
    required this.iconName,
    this.color = Colors.black,
    this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      child: IconButton(
        onPressed: onPressed,
        icon: XSvgImage.load(
          iconName,
          width: 28,
          height: 28,
          color: color,
        ),
        style: ButtonStyle(
          padding: WidgetStateProperty.all(EdgeInsets.zero),
          // 添加点击效果优化
          overlayColor: WidgetStateProperty.resolveWith<Color?>(
            (Set<WidgetState> states) {
              if (states.contains(WidgetState.pressed)) {
                return Colors.grey.withValues(alpha: 0.1);
              }
              return null;
            },
          ),
        ),
      ),
    );
  }
}
